<template>
  <view class="container">
    <!-- 头部 -->
    <view class="head"
      style="background-color: #ffcc00;
      height: 180rpx;
      display: flex;">
      <img
        style="height: 50rpx;
        width: 50rpx;
        padding: 10rpx;
        margin-top: 15%;"  
        src="../../../../../static/tabbar/返回.png" 
        alt="" 
        @click="handleBack"
      />
      <view style="
        height: fit-content;
        margin-top: 15%;
        margin-left: 30%;
        font-size: 32rpx;"
      >{{ buttonName }}</view>
    </view>

    <!-- 内容区域 -->
    <view class="content-wrapper">
      <!-- 左侧按钮列表 -->
      <view class="left-panel">
        <view 
          v-for="button in buttons" 
          :key="button.id"
          class="button-item"
          :class="{ active: activeButtonId === button.id }"
          @click="handleButtonClick(button)"
        >
          <text>{{ button.name }}</text>
        </view>
      </view>

      <!-- 右侧内容 -->
      <view class="right-panel">
        <!-- 服务列表 -->
        <view class="service-list">
          <view 
            v-for="(service, index) in services" 
            :key="index" 
            class="service-item"
            @click="handleServiceClick(service)"
          >
            <image :src="service.externalServiceImage" class="service-image" />
            <view class="service-info">
              <text class="service-name">{{ service.serviceName }}</text>
              <text class="service-price">{{ service.priceDescription }}</text>
              <text class="service-description">{{ service.description }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { useUserStore } from '@/store';
import { getButtons} from '@/api/services/buttons';
import { getServices } from '@/api/services/services';
const buttonName = ref('');
const buttons = ref([]);
const activeButtonId = ref(null);
const services = ref([]);
const allServices = ref([]);
const userStore = useUserStore();

// 处理返回按钮点击事件
const handleBack = () => {
  uni.navigateBack();
};

const handleButtonClick = (button) => {
  activeButtonId.value = button.id;
  
  // 确保 allServices.value 有数据后再进行过滤
  if (allServices.value && allServices.value.length > 0) {
    services.value = allServices.value.filter(service => service.buttonId === button.id);
  } else {
    // 如果没有数据，尝试重新获取
    uni.$emit('updateServices', allServices.value);
  }
  
  console.log('当前按钮ID:', button.id);
  console.log('对应服务列表:', services.value);
  
  // 强制视图更新
  services.value = [...services.value];
};

const handleServiceClick = (service) => {
  uni.navigateTo({
    url: `/pages/customer-platform/index/menu/homeClean/serviceBooking?service=${encodeURIComponent(JSON.stringify(service))}`
  });
};

// 页面加载时获取数据
onLoad(async (options) => {
  // 增加参数校验
  if (options.buttonName) {
    buttonName.value = decodeURIComponent(options.buttonName);
  }

  try {
    // 获取按钮数据
    const buttonRes = await getButtons();
    buttons.value = buttonRes.data.map(button => ({
      id: button.id,
      name: button.buttonName
    }));

    // 获取服务数据
    const serviceRes = await getServices();
    allServices.value = serviceRes.data;

    // 处理初始按钮逻辑优化
    if (options.buttonId) {
      // 添加类型转换和错误处理
      const targetId = Number(options.buttonId);
      const initialButton = buttons.value.find(button => button.id === targetId);
      
      if (initialButton) {
        activeButtonId.value = initialButton.id;
        services.value = allServices.value.filter(
          service => service.buttonId === targetId // 保持类型一致
        );
        
        // 添加滚动到可见区域逻辑
        nextTick(() => {
          const index = buttons.value.findIndex(b => b.id === targetId);
          const query = uni.createSelectorQuery().in(this);
          query.select(`.button-item:nth-child(${index + 1})`).boundingClientRect();
          query.exec(res => {
            if (res[0]) {
              uni.pageScrollTo({
                scrollTop: res[0].top - 50,
                duration: 300
              });
            }
          });
        });
      } else {
        console.warn('未找到匹配的按钮:', options.buttonId);
      }
    }
  } catch (err) {
    console.error('获取数据失败:', err);
    uni.showToast({ title: '获取数据失败', icon: 'none' });
  }
});
</script>

<style scoped lang="scss">
.container {
  padding: 32rpx;
  background-color: #fff;
  min-height: 100vh;
}

.content-wrapper {
  display: flex;
  margin-top: 20rpx;
}

.left-panel {
  width: 150rpx;
  height: 80vh;
  padding: 16rpx;
  background-color: #fff;
  border-radius: 16rpx;
  margin-right: 16rpx;
  flex-shrink: 0;
  box-sizing: border-box;
  overflow-y: auto;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
  border: 1rpx solid #eee;

  .button-item {
    padding: 16rpx 0;
    text-align: center;
    font-size: 28rpx;
    color: #666;
    border-bottom: 1rpx solid #eee;
    cursor: pointer;
    transition: all 0.2s ease;

    &:last-child {
      border-bottom: none;
    }

    &.active {
      color: #ffcc00;
      font-weight: bold;
      background-color: #f8f8f8;
    }

    &:hover {
      background-color: #f5f5f5;
    }
  }
}

.right-panel {
  width: 80%;
}

.service-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.service-item {
  height: 160rpx;
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 16rpx;
}

.service-image {
  width: 200rpx;
  height: 200rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.service-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 160rpx;
  padding: 10rpx 0;
  box-sizing: border-box;
}

.service-name {
  font-size: 28rpx;
  font-weight: bold;
  height: 40rpx;
  line-height: 40rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.service-price {
  font-size: 28rpx;
  color: #ff0000;
  height: 40rpx;
  line-height: 40rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.service-description {
  font-size: 28rpx;
  color: #666;
  height: 85rpx;
  line-height: 40rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
}
</style>
